<template>
  <div class="college-table">
    <div class="tab">
      <div
        v-for="item in tabs"
        :class="['tab-item', currentTab == item.value ? 'active' : '']"
        @click="handleTabClick(item)"
      >
        {{ item.name }}
      </div>
    </div>
    <div class="table-box">
      <div class="header">
        <div class="item one">门类</div>
        <div class="item flex-space-between two">
          <span>专业名称</span>
          <span>专业代码</span>
        </div>
        <div class="item flex-space-between three">
          <span>本专业开设院校</span>
          <span class="flex-center-center tooltip-wrapper">
            <span>覆盖率</span>
            <img
              class="question-icon"
              :src="questionLogo"
              @click="showToolTip = !showToolTip"
            />
            <div class="tooltip-content" v-if="showToolTip">
              覆盖率=选科招生数/本校总招生数
            </div>
          </span>
        </div>
      </div>
      <div class="table" v-loading="loading">
        <div class="item left one" ref="leftRef">
          <div
            :class="[
              'left-item',
              currentGroup.groupName == item.groupName ? 'active' : '',
            ]"
            v-for="(item, index) in groupList"
            :key="index"
            @click="handleChangeGroup(item)"
          >
            {{ item.groupName }}
          </div>
        </div>
        <div class="item middle two" ref="middleRef">
          <div
            :class="[
              'middle-item',
              currentMajor?.groupName == item.groupName ? 'active' : '',
            ]"
            v-for="(item, index) in majorList"
            @click="handleChangeMajor(item)"
          >
            <span>{{ item.groupName }}</span>
            <span>{{ item.tagCode }}</span>
          </div>
        </div>
        <div class="item right three" ref="rightRef" v-if="collegeList.length">
          <div
            :class="['right-item', index % 2 == 0 ? 'odd' : 'even']"
            v-for="(item, index) in collegeList"
            @click="handleClickCollege(item)"
          >
            <img :src="item.icon" class="icon" alt="" />
            <div class="name-box">
              <div class="name">{{ item.collegeName }}</div>
              <div class="desc">
                {{ item.desc }}
              </div>
              <div class="tag-box">
                <div
                  class="tag-item"
                  v-for="(_item, index) in item.tags"
                  :key="index"
                >
                  {{ _item }}
                </div>
              </div>
            </div>
            <div class="rate-box">
              <el-progress
                type="circle"
                :percentage="+item.coverageRate"
                color="#0169FF"
              />
            </div>
          </div>
        </div>
        <div class="no-data empty" v-else>
          <Empty />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  computed,
  onMounted,
  defineAsyncComponent,
  onUnmounted,
} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useSubjectSelectStore } from '@/store/subjectSelect';
import { selectProList, selectCollegeList } from '@/api/subjectSelect';

const Empty = defineAsyncComponent(() => import('@/components/Empty.vue'));

const route = useRoute();
const router = useRouter();

const store = useSubjectSelectStore();

const subjectList = computed(() => store.homeData.subjectList);
const province = computed(() => store.homeData.province);

const leftRef = ref(null);
const middleRef = ref(null);
const rightRef = ref(null);

const searchAllowSubject = ref(
  subjectList.value.map((item) => {
    return item.id;
  })
);

const tabs = ref([
  {
    name: '本科',
    value: '30',
  },
  {
    name: '专科',
    value: '10',
  },
]);

const questionLogo =
  'https://img3.job1001.com/ypMp/elan/images/career/collegeVolunteer/question.png';
const showToolTip = ref(false);
const hideToolTip = () => {
  showToolTip.value = false;
};

const handleScroll = () => {
  hideToolTip();
};

// 监听点击事件（组件本身和父组件，但排除question-icon）
const handleClick = (event) => {
  // 检查点击的元素是否是 question-icon 或其子元素
  const isQuestionIcon = event.target.closest('.question-icon');
  if (!isQuestionIcon) {
    hideToolTip();
  }
};

const loading = ref(false);
const currentTab = ref('30');
const currentGroup = ref({});
const currentMajor = ref();
const groupList = ref([]);
const majorList = ref([]);
const selectProListFn = async (groupLevel) => {
  loading.value = true;
  const params = {
    localRegionId: province.value.value,
    recordYear: province.value.defaultYear,
    searchAllowSubject: searchAllowSubject.value.join(','),
    cateType: currentTab.value,
    groupLevel,
  };
  if (groupLevel == 2) {
    params.majorCategory = currentGroup.value.groupName;
  }
  const res = await selectProList(params);
  if (res.code == 200) {
    if (groupLevel == 1) {
      groupList.value = res.data;
      currentGroup.value = res.data[0];
    } else {
      majorList.value = res.data;
      currentMajor.value = res.data[0];
    }
  }
};

const collegeList = ref([]);
const selectCollegeListFn = async () => {
  try {
    loading.value = true;
    const params = {
      localRegionId: province.value.value,
      recordYear: province.value.defaultYear,
      searchAllowSubject: searchAllowSubject.value.join(','),
      groupName: currentMajor.value.groupName,
    };
    const res = await selectCollegeList(params);
    loading.value = false;
    if (res.code == 200) {
      res.data.forEach((item) => {
        item.tags = item.dualClassName.split(',');
        item.desc = `${item.collegeType || '-'} / ${item.levelName || '-'} / ${
          item.natureName || '-'
        }`;
      });
      collegeList.value = res.data;
    }
  } catch (error) {
    loading.value = false;
    console.log(error);
  }
};

const handleTabClick = async (item) => {
  currentTab.value = item.value;
  leftRef.value.scrollTo({ top: 0, behavior: 'smooth' });
  middleRef.value.scrollTo({ top: 0, behavior: 'smooth' });
  rightRef.value.scrollTo({ top: 0, behavior: 'smooth' });
  await selectProListFn(1);
  await selectProListFn(2);
  await selectCollegeListFn();
};

const handleChangeGroup = async (item) => {
  currentGroup.value = item;
  middleRef.value.scrollTo({ top: 0, behavior: 'smooth' });
  rightRef.value.scrollTo({ top: 0, behavior: 'smooth' });
  await selectProListFn(2);
  await selectCollegeListFn();
};

const handleChangeMajor = (item) => {
  currentMajor.value = item;
  rightRef.value.scrollTo({ top: 0, behavior: 'smooth' });
  selectCollegeListFn();
};

const handleClickCollege = (item) => {
  router.push({
    path: '/schoolDetail',
    query: {
      dataId: item.collegeId,
      dataName: item.collegeName,
    },
  });
};

onMounted(async () => {
  // 添加滚动事件监听器（监听组件本身和父组件的滚动）
  document.addEventListener('scroll', handleScroll, true);
  window.addEventListener('scroll', handleScroll, true);

  // 添加点击事件监听器（监听组件本身和父组件的点击）
  document.addEventListener('click', handleClick, true);
  window.addEventListener('click', handleClick, true);

  await selectProListFn(1);
  await selectProListFn(2);
  await selectCollegeListFn();
});

onUnmounted(() => {
  // 移除事件监听器
  document.removeEventListener('scroll', handleScroll, true);
  window.removeEventListener('scroll', handleScroll, true);
  document.removeEventListener('click', handleClick, true);
  window.removeEventListener('click', handleClick, true);
});
</script>

<style scoped lang="scss">
.college-table {
  .tab {
    display: flex;
    justify-content: center;
    margin-bottom: 18px;
    .tab-item {
      padding: 22px 62px;
      background: #f5f5f5;
      font-weight: bold;
      font-size: 26px;
      color: #333333;
      &:first-child {
        border-radius: 16px 0px 0px 16px;
        border-right: 1px solid #d2d2d2;
      }
      &:last-child {
        border-radius: 0px 16px 16px 0px;
      }
      &.active {
        color: #0b6eff;
        background: #f6fafe;
      }
    }
  }
  .table-box {
    margin: 0 -40px;
    .one {
      width: 310px;
    }
    .two {
      width: 600px;
    }
    .three {
      flex: 1;
      .tooltip-wrapper {
        position: relative;
        .question-icon {
          width: 20px;
          height: 20px;
          margin-left: 2px;
          cursor: pointer;
        }
        .tooltip-content {
          font-size: 22px;
          width: 220px;
          padding: 12px 24px;
          position: absolute;
          top: -100px;
          left: -198px;
          background: #fff;
          border-radius: 4px;
          box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
          z-index: 1000;
          color: #333;
        }
      }
    }
    .empty {
      flex: 1;
    }
    .header {
      display: flex;
      background: #f5f5f5;
      border-radius: 20px 20px 0px 0px;
      .item {
        padding: 13px 54px;
        font-size: 24px;
        color: #666666;
        line-height: 30px;
        box-sizing: border-box;
        &:last-child {
          padding-right: 80px;
        }
      }
    }
    .table {
      display: flex;
      height: calc(100vh - 270px);
      .item {
        height: 100%;
        overflow-y: auto;
        border-right: 1px solid #dde7f9;
        box-sizing: border-box;
      }
      .left-item {
        font-size: 26px;
        color: #666666;
        padding: 32px 54px;
        width: 310px;
        flex-shrink: 0;
        box-sizing: border-box;
        &.active {
          background: #e7f3ff;
          font-weight: bold;
          color: #0b6eff;
        }
      }
      .middle-item {
        font-size: 26px;
        color: #666666;
        padding: 32px 54px;
        background: #f6fafe;
        width: 600px;
        flex-shrink: 0;
        display: flex;
        justify-content: space-between;
        box-sizing: border-box;
        &.active {
          background: #e7f3ff;
          font-weight: bold;
          color: #0b6eff;
        }
      }
      .right-item {
        flex: 1;
        font-size: 26px;
        color: #666666;
        padding: 20px 54px;
        display: flex;
        align-items: center;
        box-sizing: border-box;
        &.odd {
          background: #f6fafe;
        }
        &.even {
          background: #f6fafe;
        }
        .icon {
          width: 96px;
          height: 96px;
          margin-right: 26px;
        }
        .name-box {
          .name {
            font-weight: bold;
            font-size: 26px;
            color: #333333;
          }
          .desc {
            font-weight: 400;
            font-size: 24px;
            color: #666666;
            margin: 10px 0 16px 0;
          }
          .tag-box {
            display: flex;
            align-items: center;
            gap: 10px;
            .tag-item {
              font-size: 22px;
              color: #666;
              background: #f0f0f0;
              border-radius: 6px;
              padding: 3px 10px;
            }
          }
        }
        .rate-box {
          margin-left: auto;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          gap: 10px;
          :deep(.el-progress-circle) {
            width: 121px !important;
            height: 121px !important;
            line-height: 121px !important;
          }
          :deep(.el-progress__text) {
            font-size: 25px !important;
          }
        }
      }
    }
  }
}
</style>
